package ils.tools;

import com.sun.org.apache.xpath.internal.NodeSet;
import ils.util.HibernateUtil;
import org.hibernate.classic.Session;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created with IntelliJ IDEA.
 * User: rejeevd
 * Date: 13/10/12
 * Time: 8:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class BooksLoader
{

    public void load()
    {
        try {
            /*Unmarshaller unmarshaller = JAXBContext.newInstance(GoodReadsBook.class).createUnmarshaller();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse("books.xml");*/

            InputSource inputSource = new InputSource(new FileInputStream("d:/temp/books.xml"));
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xPath = xPathFactory.newXPath();

            NodeList nodeList = (NodeList)xPath.evaluate("/books/book", inputSource, XPathConstants.NODESET);
            System.out.println("count: " + nodeList.getLength());
            Session session = HibernateUtil.getSessionFactory().openSession();
            Connection connection = session.connection();
            String sql = "insert into books (id, title, description, author, publisher, edition, pages, isbn, imageUrl, link, publishYear) " +
                    "values (?1, '?2', '?3', '?4', '?5', '?6', ?7, '?8', '?9', '?10', ?11)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            PreparedStatement selectStatement = connection.prepareStatement("select max(id) from books");
            ResultSet rs = selectStatement.executeQuery();
            rs.next();
            int maxid = rs.getInt(1);
            System.out.println("maxId: " + maxid);
            for(int i=0;i<nodeList.getLength();i++)
            {
                Node element = nodeList.item(i);
                //System.out.println("node: " + element.getTextContent());
                String isbn = xPath.evaluate("isbn/text()", element);
                String title = xPath.evaluate("title/text()", element);
                String imageUrl = xPath.evaluate("image_url/text()", element);
                String link = xPath.evaluate("link/text()", element);
                String numPages = xPath.evaluate("num_pages", element);
                String publisher = xPath.evaluate("publisher/text()",element);
                String description = xPath.evaluate("description/text()", element);
                NodeList authorsNodes = (NodeList)xPath.evaluate("authors", element, XPathConstants.NODESET);
                String authors = getAuthors(authorsNodes);
                String publishYear = xPath.evaluate("published/text()", element);
                String edition = xPath.evaluate("edition_information/text()", element);


                System.out.println("isbn: " + isbn);
                System.out.println("title: " + title);
                System.out.println("imageUrl: " + imageUrl);
                System.out.println("link: " + link);
                System.out.println("numPages: " + numPages);
                System.out.println("publisher: " + publisher);
                System.out.println("description: " + description);
                System.out.println("authors: " + authors);
                System.out.println("publish year: " + publishYear);
                System.out.println("edition: " + edition);
                System.out.println("\n\n\n");

                preparedStatement.setInt(1, ++maxid);
                preparedStatement.setString(2, title);
                preparedStatement.setString(3, description);
                preparedStatement.setString(4, authors);
                preparedStatement.setString(5, publisher);
                preparedStatement.setString(6, edition);
                preparedStatement.setString(7, numPages);
                preparedStatement.setString(8, isbn);
                preparedStatement.setString(9, imageUrl);
                preparedStatement.setString(10, link);
                preparedStatement.setString(11,  publishYear);
                preparedStatement.execute();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getAuthors(NodeList nodes) throws Exception
    {
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        String authors = null;
        for(int i=0;i<nodes.getLength();i++)
        {
            String name = xPath.evaluate("author/name/text()", nodes.item(i));
            if(authors == null) authors = name;
            else authors = authors + ", " + name;
        }
        return authors;
    }

    public static void main(String[] args)
    {
        new BooksLoader().load();
    }
}
